package com.changpei.common.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义List分页工具
 *
 * @author Way on 2021/9/4
 */
public class PageUtil {

    public static <T> List<T> startPage(List<T> list, Integer pageNum,
                                    Integer pageSize) {
        if (list.isEmpty()) {
            return new ArrayList<>();
        }

        // 记录总数
        int count = list.size();

        // 页数
        int pageCount;

        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        if (pageNum > pageCount) {
            return new ArrayList<>();
        }

        // 开始索引
        int fromIndex;

        // 结束索引
        int toIndex;

        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }

        return list.subList(fromIndex, toIndex);
    }
}
